package com.blustreaksw.cyclecoach.main;

import java.util.ArrayList;
import java.util.Calendar;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.blustreaksw.cyclecoach.MainActivity;
import com.blustreaksw.cyclecoach.MainActivity.UpdateCentralNavigationScreenDataCallback;
import com.blustreaksw.cyclecoach.R;
import com.blustreaksw.cyclecoach.data.UserProfile;
import com.blustreaksw.cyclecoach.data.WorkoutDatabaseHelper;

public class Fragment_WorkoutSelection extends Fragment {
	
	private static final String TAG = "Fragment_WorkoutSelection";
	private static final double KM_TO_MILES = 0.621371;
	private static final long MILLISEC_IN_30_DAYS = 86400000;
	
	//Button mSelectBikeProfileButton;
	//Button mSelectWorkoutButton;
	Button mStartWorkoutButton;
	ImageView mHrmStatusIndicator;
	ImageView mCscStatusIndicator;
	ImageView mPowerStatusIndicator;
	
	TextView mFragment_workoutStats_30day_sessionCount;
	TextView mFragment_workoutStats_30day_time;
	TextView mFragment_workoutStats_30day_distance;
	
	TextView mFragment_workoutStats_lifetime_sessionCount;
	TextView mFragment_workoutStats_lifetime_time;
	TextView mFragment_workoutStats_lifetime_distance;

	@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_configure_workout, container, false);
        
        //mSelectBikeProfileButton = (Button) v.findViewById(R.id.fragment_workoutConfig_selectBikeProfileButton);
        //mSelectWorkoutButton = (Button) v.findViewById(R.id.fragment_workoutConfig_selectWorkoutButton);
        
        mStartWorkoutButton = (Button) v.findViewById(R.id.fragment_workoutConfig_startWorkoutButton);
        mStartWorkoutButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO
				// We should be checking here if the BTLE devices are all ready to go and
				// notify the user if there is a problem.
				
				Fragment fragment;
				if((fragment = getActivity().getSupportFragmentManager().
						findFragmentByTag(MainActivity.FRAGMENT_ACTIVE_WORKOUT)) == null) {
					fragment = new Fragment_ActiveWorkout();
				}
			
				getActivity().getSupportFragmentManager().beginTransaction()
					.replace(R.id.fragmentContainer, fragment, MainActivity.FRAGMENT_CENTRAL_CONTROL)
					.addToBackStack(null)
					.commit();
			}
		});
        
        mHrmStatusIndicator = (ImageView)v.findViewById(R.id.image_indicatorHRM);
        mCscStatusIndicator = (ImageView)v.findViewById(R.id.image_indicatorCSC);
        mPowerStatusIndicator = (ImageView)v.findViewById(R.id.image_indicatorPOWER);
        
        mFragment_workoutStats_30day_sessionCount = (TextView)v.findViewById(R.id.fragment_workoutStats_30day_sessionCount);
    	mFragment_workoutStats_30day_time = (TextView)v.findViewById(R.id.fragment_workoutStats_30day_time);
    	mFragment_workoutStats_30day_distance = (TextView)v.findViewById(R.id.fragment_workoutStats_30day_distance);
    	
    	mFragment_workoutStats_lifetime_sessionCount = (TextView)v.findViewById(R.id.fragment_workoutStats_lifetime_sessionCount);
    	mFragment_workoutStats_lifetime_time = (TextView)v.findViewById(R.id.fragment_workoutStats_lifetime_time);
    	mFragment_workoutStats_lifetime_distance = (TextView)v.findViewById(R.id.fragment_workoutStats_lifetime_distance);
    	
    	if(((MainActivity)getActivity()).isWorkoutActive()) {
			Fragment fragment;
			if((fragment = getActivity().getSupportFragmentManager().
					findFragmentByTag(MainActivity.FRAGMENT_ACTIVE_WORKOUT)) == null) {
				fragment = new Fragment_ActiveWorkout();
			}
		
			getActivity().getSupportFragmentManager().beginTransaction()
				.replace(R.id.fragmentContainer, fragment, MainActivity.FRAGMENT_CENTRAL_CONTROL)
				.addToBackStack(null)
				.commit();
		}
        
        return v;
    }
	
	@Override
	public void onResume() {
		super.onResume();
		((MainActivity)getActivity()).registerCentralNavigationCallback(mUpdateCentralNavigationScreenDataCallback);
		
		ArrayList<Long> lStats = new ArrayList<Long>();
		ArrayList<Double> dStats = new ArrayList<Double>();
		
		WorkoutDatabaseHelper.getInstance(getActivity()).getWorkoutStatistics(((MainActivity)getActivity()).getUserProfile().getId(), 0, dStats, lStats);
		mFragment_workoutStats_lifetime_sessionCount.setText(Long.toString(lStats.get(0)));
		mFragment_workoutStats_lifetime_time.setText(epochTimeToString(lStats.get(1)));
		
		if(((MainActivity)getActivity()).getUserProfile().getDisplayUnits().equals(UserProfile.MeasurementUnits.METRIC)) {
			mFragment_workoutStats_lifetime_distance.setText(String.format("%1.2f km", dStats.get(0)));
        } else {
        	mFragment_workoutStats_lifetime_distance.setText(String.format("%1.2f miles", dStats.get(0) * KM_TO_MILES));
        }
		
		WorkoutDatabaseHelper.getInstance(getActivity()).getWorkoutStatistics(
				((MainActivity)getActivity()).getUserProfile().getId(), Calendar.getInstance().getTimeInMillis() - MILLISEC_IN_30_DAYS, dStats, lStats);
		mFragment_workoutStats_30day_sessionCount.setText(Long.toString(lStats.get(0)));
		mFragment_workoutStats_30day_time.setText(epochTimeToString(lStats.get(1)));
		
		if(((MainActivity)getActivity()).getUserProfile().getDisplayUnits().equals(UserProfile.MeasurementUnits.METRIC)) {
			mFragment_workoutStats_30day_distance.setText(String.format("%1.2f km", dStats.get(0)));
        } else {
        	mFragment_workoutStats_30day_distance.setText(String.format("%1.2f miles", dStats.get(0) * KM_TO_MILES));
        }
		
	}
	
	
	private String epochTimeToString(long millisec) {
		StringBuilder timeElapsedFormatted = new StringBuilder();
		long secondsElapsed = millisec/ 1000;
		long minutesElapsed = (secondsElapsed / 60) % 60; 
		long hoursElapsed = (secondsElapsed / 3600) % 24;
		long daysElapsed = secondsElapsed / 86400;
		
		timeElapsedFormatted.insert(0, String.format("%02d", secondsElapsed % 60));
		timeElapsedFormatted.insert(0, String.format("%02d:", minutesElapsed));
		if(hoursElapsed > 0) {
			timeElapsedFormatted.insert(0, String.format("%02d:", hoursElapsed));
		}
		if(daysElapsed > 0) {
			timeElapsedFormatted.insert(0, String.format("%d days, ", daysElapsed));
		}
		
		return timeElapsedFormatted.toString();
	}
	
	@Override
	public void onPause() {
		super.onPause();
		((MainActivity)getActivity()).deregisterCentralNavigationCallback();
	}
	
	
	private UpdateCentralNavigationScreenDataCallback mUpdateCentralNavigationScreenDataCallback = new UpdateCentralNavigationScreenDataCallback() {
		public void hrmStatusUpdate(boolean connected) {
			if(connected) {
				mHrmStatusIndicator.setImageResource(R.drawable.ic_heart);
			} else {
				mHrmStatusIndicator.setImageResource(R.drawable.ic_heart_offline);
			}
		}
		public void cscStatusUpdate(boolean connected) {
			if(connected) {
				mCscStatusIndicator.setImageResource(R.drawable.ic_speedometer);
			} else {
				mCscStatusIndicator.setImageResource(R.drawable.ic_speedometer_offline);
			}
		}
		public void powerStatusUpdate(boolean connected) {
			if(connected) {
				mPowerStatusIndicator.setImageResource(R.drawable.ic_power);
			} else {
				mPowerStatusIndicator.setImageResource(R.drawable.ic_power_offline);
			}
		}
	};
}
